package net.funafuna.funamail;

import java.io.UnsupportedEncodingException;

public class Base64 {

    private static final char[] BASE64_MAPPING_TABLE = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
            'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+',
            '/' };

    public static String encode(String str) {
        return encode(str.getBytes());
    }

    public static String encode(String str, String encode) throws UnsupportedEncodingException {
        return encode(str.getBytes(encode));
    }

    public static String encode(byte[] bytes) {
        final int byteLnegth = bytes.length;
        if (byteLnegth == 0) {
            return "";
        }
        final int len;
        if (byteLnegth % 3 == 0) {
            len = byteLnegth / 3 * 4;
        } else {
            len = (byteLnegth / 3 + 1) * 4;
        }
        final StringBuilder sb = new StringBuilder(len);
        int temp = 0;
        int counter = 0;
        for (final byte b : bytes) {
            if (counter == 3) {
                counter = 0;
            }
            counter++;
            if (counter == 1) {
                temp = b >>> 2 & 0x0000003F;
                sb.append(BASE64_MAPPING_TABLE[temp]);
                temp = b << 4 & 0x00000030;
            } else if (counter == 2) {
                temp = b >>> 4 & 0x0000000F | temp;
                sb.append(BASE64_MAPPING_TABLE[temp]);
                temp = b << 2 & 0x0000003C;
            } else {
                temp = b >>> 6 & 0x00000003 | temp;
                sb.append(BASE64_MAPPING_TABLE[temp]);
                temp = b & 0x0000003F;
                sb.append(BASE64_MAPPING_TABLE[temp]);
            }
        }
        if (counter == 1 || counter == 2) {
            sb.append(BASE64_MAPPING_TABLE[temp]);
        }
        final int addLength = (4 - sb.length() % 4) % 4;
        for (int i = 0; i < addLength; i++) {
            sb.append('=');
        }
        return sb.toString();
    }

}
